package com.dtu.distributed.connection;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.rmi.RemoteException;
import java.util.Map.Entry;

import com.dtu.distributed.controller.BullyAlgorithmControlller;
import com.dtu.distributed.controller.TempController;
import com.dtu.distributed.enums.Action;
import com.dtu.distributed.exception.NotAdminException;

public class AdminConnectionImpl implements AdminConnection {

	
	@Override
	public String shiftAdmin() throws RemoteException{
	
		System.out.println("Max identifier is:" + BullyAlgorithmControlller.maxIdentifier+ " own identifier is " + BullyAlgorithmControlller.ownIdentifier );
		if(BullyAlgorithmControlller.maxIdentifier==BullyAlgorithmControlller.ownIdentifier){
			System.out.println("sending out coordinater to all with lower identifiers");
			//Send "cordinater" to all other nodes in the list with lower identifier (minus the admin node) using tcp
			BullyAlgorithmControlller.sendCoordinatorToAll();
			//
			TempController.adminTemperatureIpAddress = TempController.myIpAddress;
			TempController.adminTemperaturePort = TempController.myadminTemperaturePort;
			TempController.makeAdmin(true);
			//here one can simply reply back to the End User
			return "" + BullyAlgorithmControlller.ownIdentifier;
		}
		else{
			//send "election" to all nodes with higher identifier (minus the admin) using TCP
			System.out.println("sending out election to all with higher identifiers");
			Thread listener=TempController.getAdminElectionListener();
			BullyAlgorithmControlller.sendElectionToNodes();

			return "" + BullyAlgorithmControlller.electedI;
			
		}
		
	}
	@Override
	public double getAvg() throws RemoteException, NotAdminException  {
		if(TempController.isAdmin()){
			return TempController.getAvg();
		}
		else{
			throw new NotAdminException();
		}
	}
}
